package ru.ds.selenium;

import java.util.regex.Pattern;
import java.util.concurrent.TimeUnit;
import java.util.ArrayList;
import java.util.List;

import javax.swing.plaf.basic.BasicScrollPaneUI.HSBChangeListener;

import org.testng.*;
import org.testng.annotations.*;

import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;

import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;

public class CreateDeleteMovie extends ru.ds.selenium.pages.TestBase2 {
  private boolean acceptNextAlert = true;
  private StringBuffer verificationErrors = new StringBuffer();
  private CharSequence movieName = "My new movie";
  private CharSequence secondMovieName = "My new movie 2";
  private CharSequence movieYear = "2012";
  private final String nameInput = "name";
  private final String yearInput = "year";
  private final String addPageURLSuffix = "go=add";

  @Test
  public void testCreateDeletemovie() throws Exception {
	//Login procedure
	driver.get(baseUrl + "/php4dvd/");
	WebElement usernameField = driver.findElement(By.id("username"));
	usernameField.clear();
	usernameField.sendKeys("admin");
	WebElement passwordField = driver.findElement(By.name("password"));
	passwordField.clear();
	passwordField.sendKeys("admin");
	driver.findElement(By.name("submit")).click();
	List<String> addedMoviesURLs = new ArrayList<String>();
	//Creating new movie with all required fields filled
	driver.findElement(By.linkText("Add movie")).click();
	fillNewMovieForm(movieName, movieYear);
	if(driver.getCurrentUrl().endsWith(addPageURLSuffix)){
		findAndFillRequiredFields(movieName, movieYear);
	}
	addedMoviesURLs.add(driver.getCurrentUrl());
	driver.findElement(By.linkText("Home")).click();
	//Attempting to create movie with both required field left empty
	driver.findElement(By.linkText("Add movie")).click();
	fillNewMovieForm("", "");
	//if "Add movie" URL is not changed then movie was not submitted because of the errors
	if(driver.getCurrentUrl().endsWith(addPageURLSuffix)){
		findAndFillRequiredFields(secondMovieName, movieYear);
	}
	addedMoviesURLs.add(driver.getCurrentUrl());
	driver.findElement(By.linkText("Home")).click();
	//Deleting created movies
	for(String url : addedMoviesURLs) {
		driver.get(url);
		driver.findElement(By.cssSelector("img[alt=\"Remove\"]")).click();
		assertTrue(closeAlertAndGetItsText().matches("^Are you sure you want to remove this[\\s\\S]$"));
	}
	//Logging out
    driver.findElement(By.linkText("Log out")).click();
    assertTrue(closeAlertAndGetItsText().matches("^Are you sure you want to log out[\\s\\S]$"));
  }

  private boolean isElementPresent(By by) {
    try {
      driver.findElement(by);
      return true;
    } catch (NoSuchElementException e) {
      return false;
    }
  }

  private String closeAlertAndGetItsText() {
    try {
      Alert alert = driver.switchTo().alert();
      String alertText = alert.getText();
      if (acceptNextAlert) {
        alert.accept();
      } else {
        alert.dismiss();
      }
      return alertText;
    } finally {
      acceptNextAlert = true;
    }
  }
  
  private boolean hasAttribute(WebElement we, String attrName) {
	  if(we.getAttribute(attrName) == null) {
		  return false;
	  } else {
		  return true;
	  }
  }
  
  private List<WebElement> getAllInputs() {
	  return driver.findElements(By.tagName("input"));
  }
  
  private void fillNewMovieForm(CharSequence movieName, CharSequence movieYear){
		//required text fields
		WebElement movieNameField = driver.findElement(By.name("name"));
		movieNameField.clear();
		movieNameField.sendKeys(movieName);
		WebElement movieYearField = driver.findElement(By.name("year"));
		movieYearField.clear();
		movieYearField.sendKeys(movieYear);
		//Checkboxes
		if(isElementPresent(By.id("own_no"))) {
			WebElement ownCheckBox = driver.findElement(By.id("own_no"));
			ownCheckBox.click();
		}
		if(isElementPresent(By.id("seen_yes"))) {
			WebElement seenCheckBox = driver.findElement(By.id("seen_yes"));
			seenCheckBox.click();
		}
		if(isElementPresent(By.id("loaned_no"))) {
			WebElement loanCheckBox = driver.findElement(By.id("loaned_no"));
			loanCheckBox.click();
		}
		//Submit
		WebElement submitButton = driver.findElement(By.id("submit"));
		submitButton.click();
  }
  
  private void findAndFillRequiredFields(CharSequence movieName, CharSequence movieYear) {
		for(WebElement we : getAllInputs()) {
			if(hasAttribute(we, "name")) {
				String inputName = we.getAttribute("name");
				if(nameInput.equals(inputName)) {
					we.clear();
					we.sendKeys(movieName);
				}
				if(yearInput.equals(inputName)) {
					we.clear();
					we.sendKeys(movieYear);
				}
			}	
		}
		WebElement submitButton = driver.findElement(By.id("submit"));
		submitButton.click();
  }
}



